import Classify from "@/components/Article/Classify"
import News from '@/components/Article/News'
import { getNewsDetail, getRecommendNews, getSlideVideoBack, getNewsList, getNewsTypesList } from '@/server/news'
import Layout from '@/components/Layout'
import { pinyin } from 'pinyin-pro';

const Article = ({ page, ...props }) => {
  return (
    <>
      {
        page === 'news' ? <News {...props}></News> : <Classify {...props}></Classify>
      }
    </>
  )
}


Article.getLayout = (page, props) => {
  return (
    <Layout header footer {...props}>
      {page}
    </Layout >
  )
}


export async function getServerSideProps (ctx) {
  const id = ctx.params?.id?.[0]

  let [newsNavList] = await Promise.all([getNewsTypesList()])
  newsNavList = newsNavList.map(row => ({ ...row, en: pinyin(row?.newsTypeName, { toneType: 'none', type: "array" }).join("") }))

  if (ctx.params?.id && !isNaN(parseFloat(id)) && isFinite(id)) {
    //文章详情页
    const [newsDetail, recommendNewsData, videoList] = await Promise.all([getNewsDetail(id), getRecommendNews({ pageSize: 6, pageNum: 1 }), getSlideVideoBack({ num: 6, type: 3 })])
    return {
      props: {
        newsDetail,
        recommendNewsData: recommendNewsData?.records || [],
        videoList,
        type: newsDetail?.news?.typeId,
        page: "news"
      }
    }
  } else {
    //分类页面
    const params = {
      pageNum: ctx.query?.page || 1,
      pageSize: 8,
      id: newsNavList[0]?.id,
      en: id || newsNavList[0]?.en
    }
    const item = newsNavList.find(row => id === row?.en)
    item && Reflect.set(params, "id", item?.id)
    const [recommendNewsData, videoList, everybody, res] = await Promise.all([getRecommendNews({ pageSize: 6, pageNum: 1 }), getSlideVideoBack({ num: 6, type: 3 }), getNewsList(params.id, params.pageNum, params.pageSize), getNewsList(params.id, params.pageNum, params.pageSize)])
    if (ctx.query?.page && ctx.query?.page > 0) params.pageNum = Number(ctx.query?.page)
    params.total = res.total
    params.current = res.current
    return {
      props: {
        params,
        initNews: res?.records,
        recommendNewsData: recommendNewsData?.records,
        videoList,
        everybody: everybody?.records,
        everybodyId: params.id,
        page: "classify",
      }
    }
  }
}
export default Article